package cn.lds.j368.dsbank.controller;

import cn.lds.j368.dsbank.annotation.SysLogAnnotation;
import cn.lds.j368.dsbank.constant.DsBankConstants;
import cn.lds.j368.dsbank.domain.*;
import cn.lds.j368.dsbank.dto.RespDTO;
import cn.lds.j368.dsbank.exception.ServiceException;
import cn.lds.j368.dsbank.exception.ValidatorException;
import cn.lds.j368.dsbank.service.CustomerService;
import cn.lds.j368.dsbank.service.DataDictionaryService;
import cn.lds.j368.dsbank.service.LoanApplyService;
import cn.lds.j368.dsbank.service.LoanProduceService;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("loan")
public class LoanApplyController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private LoanProduceService loanProduceService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private LoanApplyService loanApplyService;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    private Logger log = LoggerFactory.getLogger(LoanApplyController.class);


    @GetMapping("show_loans_apply")
    @SysLogAnnotation(operUrl = "/loan/show_loans_apply",operModul = "/loan_apply",operType = "查询",operDesc = "查询贷款申请")
    public String showLoanApplyList(Model model) throws ServiceException {


        RespDTO<List<LoanApply>> listRespDTO = loanApplyService.selectLoanApplyAll();

        model.addAttribute("results",listRespDTO);

        return "/loan_apply/show_loan_apply";
    }

    @GetMapping("show_loans_apply_detail/{laId}")
    @SysLogAnnotation(operUrl = "/loan/show_loans_apply_detail",operModul = "/loan_apply",operType = "查询",operDesc = "查询贷款申请详情")
    public String showLoanApplyDetail(Model model,@PathVariable("laId") Long loanApplyId) throws ServiceException {


        RespDTO<LoanApply> loanApplyRespDTO = loanApplyService.selectLoanApplyByApplyId(loanApplyId);

        model.addAttribute("result",loanApplyRespDTO);

        return "/loan_apply/show_apply_details";
    }



    @GetMapping("add_apply/{customerId}")
    @SysLogAnnotation(operUrl = "/loan/add_apply",operModul = "/loan_apply",operType = "添加",operDesc = "添加贷款申请页面")
    public String addLoanApply(@PathVariable Long customerId, Model model, HttpSession session) throws ServiceException {
        //查询出需要申请贷款的用户
        Customer customer = customerService.selectCustomerByCustomerId(customerId).getData();

        model.addAttribute("customer",customer);

        //查询出可以申请的贷款产品
        List<LoanProduce> loanApplyProduce = loanProduceService.selectLoanProduceAll().getData();

        model.addAttribute("loanApplyProduce",loanApplyProduce);


        //通过数据字典查询抵押物类型
        List<DataDictionary> collateralTypes = dataDictionaryService.selectDataByTypeCode("COLLATERALTYPE");
        model.addAttribute("collateralTypes",collateralTypes);

        //通过数据字典查询还款方式
        List<DataDictionary> repaymentModes = dataDictionaryService.selectDataByTypeCode("REPAYMENT_MODE");

        model.addAttribute("repaymentModes",repaymentModes);


        return "/loan_apply/add_loan_apply";

    }
    @PostMapping("/do_add_loan_apply")
    @SysLogAnnotation(operUrl = "/loan/do_add_apply",operModul = "/loan_apply",operType = "添加",operDesc = "提交添加贷款申请")
    public String doAddCustomer(@Validated LoanApply loanApply, @Valid @NotBlank(message = "没有上传身份照片") MultipartFile dywCertificateImg, @AuthenticationPrincipal Employee employee, BindingResult errors) throws ValidatorException, ServiceException, IOException {

        log.info("抵押物凭证:{}",dywCertificateImg.getOriginalFilename());

        //获取上传文件的文件名
        String originalFilename = dywCertificateImg.getOriginalFilename();
        //获取上传文件的文件格式的mine
        String contentType = dywCertificateImg.getContentType();
        //如果文件格式不符合我们规定的文件格式，抛出异常
        if (!DsBankConstants.upload.CONTENT_TYPES.contains(contentType)){
            throw new ServiceException("上传文件格式不合法");
        }

        //如果上传文件为空
        try {
            BufferedImage image = ImageIO.read(dywCertificateImg.getInputStream());
            if (Objects.isNull(image)){
                throw new ServiceException("长传文件内容不合法");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



        //获取文件名的后缀名
        String ext = StringUtils.substringAfterLast(originalFilename, ".");

        //保存文件到服务器
        StorePath storePath = fastFileStorageClient.uploadFile(dywCertificateImg.getInputStream(), dywCertificateImg.getSize(), ext, null);
        //将上传文件的路径保存在customer对象中
        loanApply.setCollatrealCertificateImg("http://116.204.64.13/" + storePath.getFullPath());


//        String path = request.getServletContext().getRealPath("/certificateFileImgs");
        //我们默认创建员工id为1
        loanApply.setCreateEmpId(employee.getEmpId());

        if (errors.hasErrors()){
            //获取错误信息
            List<FieldError> fieldErrors = errors.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                throw new ValidatorException(fieldError.getField() + fieldError.getDefaultMessage());
            }
        }

        log.info("贷款申请数据：{}",loanApply);

        loanApplyService.addOrModifyLoanApply(loanApply);

        return "redirect:/loan/show_loans_apply";
    }
}
